import React, { useEffect, useState } from 'react';
import { Card, Table, Button, Space, Modal, Form, Input, Select, message } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-layout';
import { getUniversityMajorList, addUniversityMajor, updateUniversityMajor, deleteUniversityMajor } from '@/services/universityMajor';
import { getUniversityList } from '@/services/university';
import { getMajorList } from '@/services/major';
import { App } from 'antd';

const { Option } = Select;

const UniversityMajor: React.FC = React.forwardRef((props, ref) => {
  const { message } = App.useApp();
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<any[]>([]);
  const [universities, setUniversities] = useState<any[]>([]);
  const [majors, setMajors] = useState<any[]>([]);
  const [modalVisible, setModalVisible] = useState(false);
  const [modalTitle, setModalTitle] = useState('');
  const [currentRecord, setCurrentRecord] = useState<any>(null);

  const columns = [
    {
      title: '大学名称',
      dataIndex: 'universityName',
      key: 'universityName',
    },
    {
      title: '专业名称',
      dataIndex: 'majorName',
      key: 'majorName',
    },
    {
      title: '招生年份',
      dataIndex: 'enrollYear',
      key: 'enrollYear',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => (
        <span style={{ color: status === '0' ? '#52c41a' : '#ff4d4f' }}>
          {status === '0' ? '正常' : '停用'}
        </span>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: any) => (
        <Space size="middle">
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button
            type="link"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  const fetchData = async () => {
    setLoading(true);
    try {
      const response = await getUniversityMajorList();
      setData(response.data);
    } catch (error) {
      message.error('获取数据失败');
    }
    setLoading(false);
  };

  const fetchUniversities = async () => {
    try {
      const response = await getUniversityList();
      setUniversities(response.data);
    } catch (error) {
      message.error('获取大学列表失败');
    }
  };

  const fetchMajors = async () => {
    try {
      const response = await getMajorList();
      setMajors(response.data);
    } catch (error) {
      message.error('获取专业列表失败');
    }
  };

  useEffect(() => {
    fetchData();
    fetchUniversities();
    fetchMajors();
  }, []);

  useEffect(() => {
    if (modalVisible) {
      form.resetFields();
      if (currentRecord) {
        form.setFieldsValue({
          ...currentRecord,
          universityId: currentRecord.universityId?.toString(),
          majorId: currentRecord.majorId?.toString(),
          status: currentRecord.status || '0'
        });
      } else {
        form.setFieldsValue({
          status: '0'
        });
      }
    }
  }, [form, modalVisible, currentRecord]);

  const handleAdd = () => {
    setModalTitle('新增大学专业关联');
    setCurrentRecord(null);
    setModalVisible(true);
  };

  const handleEdit = (record: any) => {
    setModalTitle('编辑大学专业关联');
    setCurrentRecord(record);
    setModalVisible(true);
  };

  const handleDelete = (record: any) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除"${record.universityName}-${record.majorName}"的关联吗？`,
      onOk: async () => {
        try {
          await deleteUniversityMajor(record.id);
          message.success('删除成功');
          fetchData();
        } catch (error) {
          message.error('删除失败');
        }
      },
    });
  };

  const handleModalOk = async () => {
    try {
      const values = await form.validateFields();
      if (currentRecord) {
        await updateUniversityMajor({ ...values, id: currentRecord.id });
        message.success('更新成功');
      } else {
        await addUniversityMajor(values);
        message.success('添加成功');
      }
      setModalVisible(false);
      fetchData();
    } catch (error) {
      message.error('操作失败');
    }
  };

  return (
    <PageContainer>
      <Card>
        <div style={{ marginBottom: 16 }}>
          <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
            新增关联
          </Button>
        </div>
        <Table
          columns={columns}
          dataSource={data}
          rowKey="id"
          loading={loading}
        />
      </Card>

      <Modal
        title={modalTitle}
        open={modalVisible}
        onOk={handleModalOk}
        onCancel={() => {
          setModalVisible(false);
          form.resetFields();
        }}
        destroyOnClose
        forceRender
      >
        <Form
          form={form}
          layout="vertical"
        >
          <Form.Item
            name="universityId"
            label="大学"
            rules={[{ required: true, message: '请选择大学' }]}
          >
            <Select placeholder="请选择大学">
              {universities.map((university: any) => (
                <Option key={university.universityId} value={university.universityId}>
                  {university.universityName}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item
            name="majorId"
            label="专业"
            rules={[{ required: true, message: '请选择专业' }]}
          >
            <Select placeholder="请选择专业">
              {majors.map((major: any) => (
                <Option key={major.majorId} value={major.majorId}>
                  {major.majorName}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item
            name="enrollYear"
            label="招生年份"
            rules={[{ required: true, message: '请输入招生年份' }]}
          >
            <Input type="number" placeholder="请输入招生年份" />
          </Form.Item>
          <Form.Item
            name="status"
            label="状态"
            initialValue="0"
          >
            <Select>
              <Option value="0">正常</Option>
              <Option value="1">停用</Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
});

UniversityMajor.displayName = 'UniversityMajor';

export default UniversityMajor; 